package com.atguigui.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 535.TinyURL 的加密与解密
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/6/29 9:03
 */
public class P535EncodeAndDecodeTinyurl {

    public static void main(String[] args) {
        Codec solution = new P535EncodeAndDecodeTinyurl().new Codec();
        // TO TEST
    }

    /**
     * 执行用时：4 ms, 在所有 Java 提交中击败了52.44%的用户
     * 内存消耗：41.3 MB, 在所有 Java 提交中击败了72.93%的用户
     */
    public class Codec {


        Map<String, String> map = new HashMap<>();

        /**
         * 返回加密后得到的 TinyURL
         *
         * @param longUrl
         * @return
         */
        public String encode(String longUrl) {

            int preUuid = longUrl.hashCode();
            String shortUrl = "http://tinyurl.com/" + preUuid;
            while (map.containsKey(shortUrl)) {
                //碰到hashcode冲突就+1
                preUuid = longUrl.hashCode() + 1;
                shortUrl = "http://tinyurl.com/" + preUuid;
            }
            map.put(shortUrl, longUrl);
            return shortUrl;
        }

        /**
         * 返回解密后得到的原本的 URL
         *
         * @param shortUrl
         * @return
         */
        public String decode(String shortUrl) {
            return map.get(shortUrl);
        }
    }
}
